package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.domain.business.BusinessCountDO;
import com.qk.domain.clue.ClueCountDO;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.BusinessService;
import com.qk.management.service.ClueService;
import com.qk.management.service.ReportOverviewService;
import com.qk.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author diva
 * @date 2025/10/15 14:53
 * @ProjectName
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class ReportOverviewServiceImpl implements ReportOverviewService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private StringRedisTemplate redisClient;

    private static final String CACHE_PORTAL_KEY_PREFIX = "qk.portal";

    @Override
    public PortalVO reportOverview() {
        ClueCountDO clueCountDO = clueMapper.selectCountClue();
        BusinessCountDO businessCountDO = businessMapper.selectCountBusiness();

        PortalVO portalVO = new PortalVO();
        BeanUtil.copyProperties(clueCountDO, portalVO);
        BeanUtil.copyProperties(businessCountDO, portalVO);
        return portalVO;
    }

    @Override
    public PortalVO reportOverviewWithCache() {
        String redisKey = CACHE_PORTAL_KEY_PREFIX + "reportOverview";
        String jsonStr = null;
        try{
            jsonStr = redisClient.opsForValue().get(redisKey);
        if(ObjectUtil.isNotEmpty(jsonStr)) {
            PortalVO vo = JSONUtil.toBean(jsonStr, PortalVO.class);
            return vo;
            }
        }catch (Exception e) {
            log.error("查询缓存异常", e);
        }
        ClueCountDO clueCountDO = clueMapper.selectCountClue();
        BusinessCountDO businessCountDO = businessMapper.selectCountBusiness();
        PortalVO portalVO = BeanUtil.copyProperties(clueCountDO,PortalVO.class);
        BeanUtil.copyProperties(businessCountDO,portalVO);
        try{
            String json = JSONUtil.toJsonStr(portalVO);
            redisClient.opsForValue().set(redisKey, json);
        }catch (Exception e) {
            log.error("缓存异常", e);
        }
        return portalVO;
    }
}
